import React, { lazy, Suspense } from "react";
import { createBrowserRouter, Navigate } from "react-router-dom";
import RouteGuard from '../components/RouteGuard';
import Home from '../pages/Home';
import Login from '../pages/Login';
import NotFound from '../pages/NotFound';

// 懒加载组件
function lazyLoad(path) {
  const Comp = lazy(() => import("../pages/" + path));
  return (
    <Suspense fallback={
      <div style={{ 
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        width: '100%',
        height: '100vh',
        fontSize: '20px',
        backgroundColor: '#d3e3fd'
      }}>
        加载中……
      </div>
    }>
      <Comp />
    </Suspense>
  );
}

// 路由列表
const routerArray = createBrowserRouter([
  { path: "/", element: <Navigate to="/login" replace /> },
  {
    path: "/login",
    element: <Login />,
    meta: {
      requireAuth: false,
      title: '登录',
      key: 'login'
    }
  },
  {
    path: "/home",
    element: <Home />,
    meta: {
      requireAuth: true,
      title: '主页面',
      key: 'home'
    },
    children: [
      // 子路由to后不写/会拼接上父级path,即 /home/dashboard ,也可写全路径
      { path: "", element: <Navigate to="dashboard" replace /> },
      { 
        path: "dashboard", 
        element: (
          // 路由守卫  lazyLoad外层一定要用 {} 包裹，表示变量，否则识别为字符串
          <RouteGuard requireAuth={true}>
            { lazyLoad("dashboard") }
          </RouteGuard>
        ),
        meta: {
          title: '仪表盘',
          key: 'dashboard',
          requireAuth: true,
        }
      },
      {
        path: "profile",
        element: (
          <RouteGuard requireAuth={true}>
            { lazyLoad("profile") }
          </RouteGuard>
        ),
        meta: {
          title: '个人资料',
          key: 'profile'
        }
      },
      {
        path: 'userlist',
        element: (
          <RouteGuard requireAuth={true}>
            { lazyLoad("userlist") }
          </RouteGuard>
        ),
        meta: {
          title: '用户列表',
          key: 'userlist'
        }
      }
    ]
  },
  {
    path: "*",
    element: <NotFound />,
  }
]);

export default routerArray;